import {Image, StyleSheet, View, Text, TouchableOpacity } from 'react-native';
import {Stack, useRouter} from "expo-router";
import AntDesign from '@expo/vector-icons/AntDesign';
import React, { useState, useEffect } from "react";
import * as Location from 'expo-location';
import MapView, { Marker } from 'react-native-maps';
import daohangIcon from "@/assets/images/activityImg/daohangIcon.png"
import addressMapBackIcon from "@/assets/images/activityImg/addressMapBackIcon.png";
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useActionSheet } from '@expo/react-native-action-sheet';
import {useSelector} from "react-redux";
import {RootState} from "@/store";
import {WebView} from "react-native-webview";

export default function addressMapScreen() {

    const router = useRouter();
    const insets = useSafeAreaInsets();

    const [location, setLocation] = useState(null);
    const { showActionSheetWithOptions } = useActionSheet();
    const [html, setHtml] = useState("")
    const [lt, setLt] = useState(0);
    const [lg, setLg] = useState(0)

    const activity = useSelector((state: RootState) => state.activityDetail);

    useEffect(() => {
        console.log('destLatitude', activity.activityDetail.destLatitude)
        console.log('destLongitude', activity.activityDetail.destLongitude)
        setLt(activity.activityDetail.destLatitude);
        setLg(activity.activityDetail.destLongitude)

        const tempHtml = `
        <!DOCTYPE html>
        <html>
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <script src="https://map.qq.com/api/gljs?v=1.exp&key=VS6BZ-V2CCG-WVAQL-QM2WG-AMJIE-NOF3Q"></script>
          <style>
            #map { width: 100vw; height: 100vh; }
           body, html {
              margin: 0;
              padding: 0;
              height: 100%;
              width: 100%;
            }
          </style>
        </head>
        <body>
          <div id="map"></div>
          <script>
             var latitude = ${activity.activityDetail.destLatitude};  // 注入外部变量
             var longitude = ${activity.activityDetail.destLongitude};  // 注入外部变量
          
            // 初始化地图
            var map = new TMap.Map('map', {
              center: new TMap.LatLng(latitude, longitude), // 地图中心点（经纬度）
              zoom: 14
            });
    
            // 添加标注点
            var marker = new TMap.MultiMarker({
              id: 'marker-layer',
              map: map,
              styles: {
                marker: new TMap.MarkerStyle({
                  width: 25, // 图标宽度
                  height: 35, // 图标高度
                  anchor: { x: 16, y: 32 }, // 锚点（调整图标位置）
                  src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png' // 自定义图标
                })
              },
              geometries: [
                {
                  id: 'm1',
                  styleId: 'marker',
                  position: new TMap.LatLng(latitude, longitude), // 标记点坐标
                  properties: {
                    title: '标记点示例'
                  }
                }
              ]
            });
    
            // 点击事件
            marker.on('click', (event) => {
              var geometry = event.geometry;
              // alert("点击了标记点: " + geometry.properties.title);
            });
          </script>
        </body>
        </html>
        `;
        setHtml(tempHtml)
    }, [activity.activityDetail])

    useEffect(() => {
        (async () => {
            let { status } = await Location.requestForegroundPermissionsAsync();
            if (status !== 'granted') {
                console.log('Permission to access location was denied');
                return;
            }

            let currentLocation = await Location.getCurrentPositionAsync({});
            setLocation(currentLocation.coords);
        })();
    }, []);

    const goMap = function () {
        const options = ['苹果地图', '高德地图', '取消'];
        const cancelButtonIndex = 2;

        showActionSheetWithOptions(
            {
                options,
                cancelButtonIndex,
            },
            (buttonIndex) => {
                if (buttonIndex === 0) {
                    alert('苹果地图');
                } else if (buttonIndex === 1) {
                    alert('高德地图');
                }
            }
        );
    };


    // console.log('activityDetailactivityDetailactivityDetail', activity.activityDetail)


    return (
        <View style={{ height: "100%", backgroundColor: "#F7F7F7" }}>
            <Stack.Screen
                options={{
                    title: '设置', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#f7f7f7', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerShown: false,
                    headerLeft: () => (
                        <TouchableOpacity onPress={() => router.back()}>
                            <AntDesign name="left" size={19} color="#333" />
                            {/*<Ionicons name="arrow-back" size={30} color="#fff" style={{ paddingLeft: 15 }} />*/}
                        </TouchableOpacity>
                    ),
                }}
            />
            <TouchableOpacity onPress={() => router.back()} style={[styles.addressMapBackIcon, { top: insets.top }]}>
                <Image source={addressMapBackIcon} style={{ width: "100%", height: "100%" }} />
            </TouchableOpacity>

            <View style={styles.container}>
                {
                    activity?.activityDetail && (
                        <WebView originWhitelist={['*']} source={{ html }} />
                        // <MapView
                        //     style={{ flex: 1 }}
                        //     region={{
                        //         latitude: activity.activityDetail.destLatitude,  // 默认显示北京
                        //         longitude: activity.activityDetail.destLongitude, // 默认显示北京
                        //         latitudeDelta: 0.09, // 更小的值可以更大程度地放大到县级
                        //         longitudeDelta: 0.09, // 尝试从更小的缩放级别开始
                        //     }}
                        //     zoomLevel={10}
                        // >
                        //     <Marker
                        //         coordinate={{
                        //             latitude: activity.activityDetail.destLatitude,
                        //             longitude: activity.activityDetail.destLongitude,
                        //         }}
                        //         title={activity.activityDetail.destName}
                        //         description={activity.activityDetail.destName}
                        //     />
                        // </MapView>
                    )
                }
                <View style={styles.botNavContainer}>
                    <View>
                        <View>
                            <Text style={styles.addressTitle}>
                                { activity?.activityDetail?.destName }
                            </Text>
                        </View>
                        <View style={styles.addressContent}>
                            <Text style={styles.addressContentText}>
                                { activity?.activityDetail?.destName }
                            </Text>
                        </View>
                    </View>
                    <TouchableOpacity onPress={goMap}>
                        <View style={styles.daohangContainer}>
                            <View style={styles.daohangWrap}>
                                <Image source={daohangIcon} style={{ width: "100%", height: "100%" }} />
                            </View>
                            <View style={styles.daohangContent}>
                                <Text style={styles.daohangContentText}>导航</Text>
                            </View>
                        </View>
                    </TouchableOpacity>
                </View>
            </View>
        </View>

    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    map: {
        width: '100%',
        height: '100%',
    },
    botNavContainer: {
        position: "absolute",
        bottom: 0,
        width: "100%",
        backgroundColor: "#fff",
        flexDirection: "row",
        justifyContent: "space-between",
        paddingBottom: 62,
        paddingTop: 20,
        paddingHorizontal: 12,
    },
    addressTitle: {
        fontSize: 14,
        color: "#2A2B30",
        fontWeight: "bold",
    },
    addressContent: {
        marginTop: 2,
    },
    addressContentText: {
        fontSize: 12,
        color: "#2A2B30"
    },
    daohangContainer: {
    },
    daohangWrap: {
        width: 36,
        height: 36,
    },
    daohangContent: {
        marginTop: 2,
    },
    daohangContentText: {
      fontSize: 10,
      color: "#676978",
      textAlign: 'center'
    },
    addressMapBackIcon: {
        width: 36,
        height: 36,
        position: "absolute",
        zIndex:99,
        marginLeft: 12,
    },
});
